package com.nagornyi.uc.action;

import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.nagornyi.uc.dao.DAOFacade;
import com.nagornyi.uc.dao.ITicketDAO;
import com.nagornyi.uc.dao.IUserDAO;
import com.nagornyi.uc.entity.Ticket;
import com.nagornyi.uc.entity.User;
import com.nagornyi.uc.transport.ActionRequest;
import com.nagornyi.uc.transport.ActionResponse;

import java.util.List;
import java.util.Locale;

/**
 * @author Nagornyi
 * Date: 02.06.14
 */
@Authorized
public class GetAllTicketsAction implements Action {

    @Override
    public void perform(ActionRequest req, ActionResponse resp) throws JSONException {
        String email = (String)req.getSession().getAttribute("email");
        Locale locale = req.getLocale();

        User user = ((IUserDAO)DAOFacade.getDAO(User.class)).getUserByEmail(email);

        List<Ticket> tickets = ((ITicketDAO)DAOFacade.getDAO(Ticket.class)).getTicketsByUser(user);

        JSONObject respObj = new JSONObject();
        JSONArray ticketObjs = new JSONArray();
        for (Ticket ticket: tickets) {
            ticketObjs.put(ticket.toJSON(locale));
        }

        respObj.put("tickets", ticketObjs);

        resp.setDataObject(respObj);
    }
}
